package com.hrg.rds.infra.executor;

import cn.hutool.core.util.StrUtil;
import com.hrg.rds.biz.config.RdsConfiguration;
import com.hrg.rds.biz.robot.domain.AgvVo;
import com.hrg.rds.biz.waybill.domain.instance.AgvMsg;
import com.hrg.rds.biz.waybill.domain.instance.WaybillInstanceStatus;
import com.hrg.rds.biz.waybill.domain.instance.WaybillInstanceVo;
import lombok.Builder;
import lombok.Data;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Builder
@Data
public class CmdInstanceContext {
	private String waybillInstanceId;
	private String cmdInstanceId;
	private String cmdId;
	private static final Map<String, WaybillInstanceVo> map = new ConcurrentHashMap<>();
	private static final Map<String, AgvVo> AgvIpMap = RdsConfiguration.AgvIpMap;
	private AgvMsg lastAgvMsg;

	public CmdInstanceContext setWaybillInstanceVo(WaybillInstanceVo waybillInstanceVo) {
		map.put(waybillInstanceId, waybillInstanceVo);
		return this;
	}
	public WaybillInstanceVo getWaybillInstanceVo() {
		return map.get(waybillInstanceId);
	}
	public void removeWaybillInstanceVo() {
		map.remove(waybillInstanceId);
	}

	/*public boolean getException() {
		return map.get(waybillInstanceId).getWaybillInstanceStatus().equals(WaybillInstanceStatus.Exception);
	}
	public void setException() {
		map.get(waybillInstanceId).setWaybillInstanceStatus(WaybillInstanceStatus.Exception);
	}*/

	public boolean getTerminated() {
		return map.get(waybillInstanceId).getWaybillInstanceStatus().equals(WaybillInstanceStatus.Terminated);
	}
	public void setTerminated() {
		map.get(waybillInstanceId).setWaybillInstanceStatus(WaybillInstanceStatus.Terminated);
	}

	public static void setTerminated(String waybillInstanceId) {
		map.get(waybillInstanceId).setWaybillInstanceStatus(WaybillInstanceStatus.Terminated);
	}

	public boolean checkIfNotExit() {
		WaybillInstanceVo waybillInstanceVo = map.get(waybillInstanceId);
		return //!waybillInstanceVo.getWaybillInstanceStatus().equals(WaybillInstanceStatus.Exception) &&
				!waybillInstanceVo.getWaybillInstanceStatus().equals(WaybillInstanceStatus.Terminated);
	}

	public boolean checkIfExit() {
		WaybillInstanceVo waybillInstanceVo = map.get(waybillInstanceId);
		return //waybillInstanceVo.getWaybillInstanceStatus().equals(WaybillInstanceStatus.Exception) ||
				waybillInstanceVo.getWaybillInstanceStatus().equals(WaybillInstanceStatus.Terminated);
	}

	public AgvVo getAgvVo() {
		if (StrUtil.isNotBlank(map.get(waybillInstanceId).getAgvId())) {
			return AgvIpMap.values().stream().filter(agvVo -> agvVo.getId().equals(map.get(waybillInstanceId).getAgvId())).toList().getFirst();
		}
		return null;
	}
}
